<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button flex felx_align">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
        <div class="guidetext" @click="imgShow = true"><i class="iconfont iconiconfontwenhao1 guide"></i>操作指引</div>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="批次" value="batch"></el-option>
              <el-option label="归属" value="username"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 设备归属管理table -->
    <el-table stripe style="width: 100%" :data="tableData" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="545">
      <el-table-column v-if="colData[0].istrue" min-width="100" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="100" align="center" prop="batch" label="SN码批次"></el-table-column>
      <!-- <el-table-column v-if="colData[2].istrue" min-width="30" align="center" prop="status" label="类型">
        <template slot-scope="scope">{{scope.row.status ? '黑名单' : '白名单'}}</template>
      </el-table-column> -->
      <el-table-column v-if="colData[2].istrue" min-width="120" align="center" prop="white_addr" label="允许上网网址"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="120" align="center" prop="black_addr" label="禁止上网网址"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="120" align="center" prop="white_ip" label="IP白名单"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="120" align="center" prop="black_ip" label="IP黑名单"></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdBrowser(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="deleteShow(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 添加dialog表单 -->
    <div>
      <el-dialog :title="editSubjects ? '网址黑白名单管控设置' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
        <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
          <el-form-item label="SN码批次:" label-width="100px" prop="batch" >
            <el-select v-model="addForm.batch" placeholder="没有选中任何项" class="add_select" multiple filterable>
              <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型:" label-width="100px" prop="status">
            <!-- <el-radio v-model="addForm.status" :label="0">白名单：全白自定义黑名单模式</el-radio> -->
            <el-radio v-model="addForm.status" :label="1">黑名单：全黑自定义白名单模式</el-radio>
          </el-form-item>
          <el-form-item label-width="100px" label="允许上网" v-for="(item,index) in addForm.addr" :key="index"  :prop="'addr.' + index + '.arr'">
            <div class="addPut">
              <el-input placeholder="请输入网址,例如www.baidu.com" v-model="item.arr"></el-input>
              <el-button class="dlePut btnLocation" round size="mini" icon="el-icon-delete" @click.prevent="removeDomain(item)"></el-button>
            </div>
          </el-form-item>

          <el-form-item label-width="100px" label="禁止上网" v-for="(items,indexs) in addForm.black_addr" :key="indexs+ 1" :rules="{ required: true, message: '请输入浏览器标签', trigger: 'blur' }"
            :prop="'black_addr.' + indexs + '.arr'">
            <div class="addPut">
              <el-input placeholder="请输入完整的网址" v-model="items.arr"></el-input>
              <el-button class="dlePut btnLocation" round size="mini" icon="el-icon-delete" @click.prevent="removeBlackDomain(items)"></el-button>
            </div>
          </el-form-item>
          <el-form-item label-width="100px" label="IP黑名单" v-for="(item,index) in addForm.black_ip" :key="index" :rules="{ required: true, message: '请输入浏览器标签', trigger: 'blur' }" :prop="'black_ip.' + index + '.arr'">
            <div class="addPut">
              <el-input placeholder="请输入完整的IP" v-model="item.arr"></el-input>
              <el-button class="dlePut btnLocation" round size="mini" icon="el-icon-delete" @click.prevent="removeBlack(item)"></el-button>
            </div>
          </el-form-item>
          <el-form-item label-width="100px" label="IP白名单" v-for="(item,index) in addForm.white_ip" :key="index" :rules="{ required: true, message: '请输入浏览器标签', trigger: 'blur' }" :prop="'white_ip.' + index + '.arr'">
            <div class="addPut">
              <el-input placeholder="请输入完整的IP" v-model="item.arr"></el-input>
              <el-button class="dlePut btnLocation" round size="mini" icon="el-icon-delete" @click.prevent="removeWhite(item)"></el-button>
            </div>
          </el-form-item>
          <el-form-item label-width="100px">
            <el-button type="primary" @click="addDomain" icon="el-icon-upload" size="mini" round>增加白名单网址</el-button>
            <el-button type="primary" @click="addBlackDomain" icon="el-icon-upload" size="mini" round>增加黑名单网址</el-button>
            <div>
              <el-button type="primary" @click="addIpwhite" icon="el-icon-upload" size="mini" round>IP白名单</el-button>
              <el-button type="primary" @click="addIpblack" icon="el-icon-upload" size="mini" round>IP黑名单</el-button>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
          <el-button v-if="editSubjects" type="primary" @click="getaddBrowser('ruleForm')" size="mini" round>确定</el-button>
          <el-button v-else type="primary" @click="geteditBrowser('ruleForm')" size="mini" round>确定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 模板操作图片弹窗 -->
    <div class="component" v-if="imgShow">
      <div class="mbImg"><img src="@/assets/images/snHmd.png" alt=""></div>
      <div class="masking" @click="imgShow = false"></div>
    </div>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryBrowserAll, queryIdBrowser, editBrowser, deleteBrowser, addBrowser } from "@/api/deployment.js";
import deleteDialog from "@/components/deleteDialog";
import { getBatchTwo } from "@/api/equipment.js";
import tableMini from '@/utils/tableMini.js'
export default {
  mixins: [tableMini],
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      validateUsername: (rule, value, callback) => {
        //  /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/
        // var reg = /^(www)\.[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
        var reg = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/i;
        if (!reg.test(value)) {
          return callback(new Error('请输入正确的网址,不用带http://或https://'))
        } else {
          callback()
        }
      },
      validateUsernames: (rule, value, callback) => {
        var reg = /^(?!http).*/
        if (!reg.test(value)) {
          return callback(new Error('请输入正确的网址,请勿以https://或http://开头'))
        } else {
          callback()
        }
      },
      checkboxVal: ["归属", "SN码批次", "允许上网网址", "禁止上网网址", "IP白名单", "IP黑名单", "创建时间"],
      //归属table
      tableData: [],
      select: "", //搜索条件
      //添加表单
      addForm: { batch: "", addr: [], black_addr: [], black_ip: [], white_ip: [], status: 1 },
      rules: {
        arr: [{ required: true, message: "请输入网址", trigger: "blur" }],
        batch: [{ required: true, message: "请选择批次", trigger: "blur" }]
      },
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      //批次下拉选择
      lotoptions: [],
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), black_addr: undefined, status: undefined, username: undefined },
      imgShow: false,
    };
  },
  created() {
    this.getTabularData()
    this.getBatchTwos()
  },
  methods: {
    //表单动态添加input
    removeDomain(item) {
      var index = this.addForm.addr.indexOf(item)
      if (index !== -1) {
        this.addForm.addr.splice(index, 1)
      }
    },
    removeBlackDomain(item) {
      var index = this.addForm.black_addr.indexOf(item)
      if (index !== -1) {
        this.addForm.black_addr.splice(index, 1)
      }
    },
    removeWhite(item) {
      var index = this.addForm.white_ip.indexOf(item)
      if (index !== -1) {
        this.addForm.white_ip.splice(index, 1)
      }
    },
    removeBlack(item) {
      var index = this.addForm.black_ip.indexOf(item)
      if (index !== -1) {
        this.addForm.black_ip.splice(index, 1)
      }
    },
    addDomain() {
      if (this.addForm.addr.length == 30) return this.$message({ type: 'warning', message: '限制30条数' })
      this.addForm.addr.push({ arr: "" })
    },
    addBlackDomain() {
      if (this.addForm.black_addr.length == 30) return this.$message({ type: 'warning', message: '限制30条数' })
      this.addForm.black_addr.push({ arr: "" })
    },
    addIpwhite() {
      if (this.addForm.white_ip.length == 30) return this.$message({ type: 'warning', message: '限制30条数' })
      this.addForm.white_ip.push({ arr: "" })
    },
    addIpblack() {
      if (this.addForm.black_ip.length == 30) return this.$message({ type: 'warning', message: '限制30条数' })
      this.addForm.black_ip.push({ arr: "" })
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteBrowser(params).then(res => {
        this.$message.success(res.msg)
        this.getTabularData()
      })
    },
    //添加浏览器信息
    getaddBrowser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.white_addr = addForm.addr.map(item => item.arr.toLowerCase()).toString()//白名单
          addForm.black_addr = addForm.black_addr.map(item => item.arr.toLowerCase()).toString()//黑名单
          addForm.black_ip = addForm.black_ip.map(item => item.arr.toLowerCase()).toString()
          addForm.white_ip = addForm.white_ip.map(item => item.arr.toLowerCase()).toString()
          addForm.batch = addForm.batch.toString()
          delete addForm.addr
          addBrowser(addForm).then(res => {
            this.$message.success(res.msg)
            this.getTabularData()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false;
        }
      });
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    //编辑浏览器信息
    geteditBrowser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.id = this.subjectId
          addForm.white_addr = addForm.addr.map(item => item.arr.toLowerCase()).toString()//白名单
          addForm.black_addr = addForm.black_addr.map(item => item.arr.toLowerCase()).toString()//黑名单
          addForm.black_ip = addForm.black_ip.map(item => item.arr.toLowerCase()).toString()
          addForm.white_ip = addForm.white_ip.map(item => item.arr.toLowerCase()).toString()
          addForm.batch = addForm.batch.toString()
          delete addForm.addr
          editBrowser(addForm).then(res => {
            this.dialogFormVisible = false
            this.$message.success(res.msg)
            this.getTabularData()
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //根据ID获取浏览器网址信息
    getqueryIdBrowser(id) {
      this.editSubjects = false
      this.subjectId = id
      queryIdBrowser({ id: id }).then(res => {
        this.dialogFormVisible = true
        let data = res.data
        //this.addForm.addr = data.addr.split(',').map(item => { return { 'arr': item } })
        // let white_addr = data.white_addr ? data.white_addr.split(',') : []
        // let white_type = white_addr.map(item => 1)
        // let black_addr = data.black_addr ? data.black_addr.split(',') : []
        // let black_type = black_addr.map(item => 2)
        // let black = this.arrayObjer(black_addr, black_type)
        // let white = this.arrayObjer(white_addr, white_type)
        this.addForm.addr = data.white_addr ? data.white_addr.split(',').map(item => { return { 'arr': item } }) : []
        this.addForm.black_addr = data.black_addr ? data.black_addr.split(',').map(item => { return { 'arr': item } }) : []
        this.addForm.black_ip = data.black_ip ? data.black_ip.split(',').map(item => { return { 'arr': item } }) : []
        this.addForm.white_ip = data.white_ip ? data.white_ip.split(',').map(item => { return { 'arr': item } }) : []
        this.addForm.batch = data.batch.split(',')
        this.addForm.status = data.status
      }).catch(err => { })
    },
    arrayObjer(arrs, checkbox) {
      let arr = JSON.parse(JSON.stringify(arrs));
      const zip = ([x, ...xs], [y, ...ys]) => {
        if (x === undefined || y === undefined) return [];
        return [[x, y], ...zip(xs, ys)];
      };
      return zip(arr, checkbox).map(([arr, type]) => ({ arr, type }));
    },
    getTabularData() {
      queryBrowserAll(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = { batch: "", addr: [], black_addr: [], black_ip: [], white_ip: [], status: 1 }
      })
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    }
  }
};
</script>

<style scoped>
/deep/ .el-dialog__header {
  transform-origin: 50% 100%;
  border-bottom: 0.5px solid #e9e9e9;
}
</style>
